package com.bbbug.coree.websocketservice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbbug.coree.service.RooominfoService;
import com.bbbug.coree.task.SongTask;
import com.bbbug.coree.utils.MiscUtil;
import com.bbbug.coree.utils.SpringUtils;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
@CrossOrigin(origins ="${myweb-path}" )
@ServerEndpoint(value = "${netty-websocket.path}",port = "${netty-websocket.port}")
public class core {
    public static ConcurrentHashMap<String, ConcurrentHashMap<String,Session>> CHATMAP =new ConcurrentHashMap<>();
    private final RedisTemplate redisTemplate=SpringUtils.getBean("redistemp");
    private final RooominfoService rooominfoService=SpringUtils.getBean(RooominfoService.class);
    @OnOpen
    public void onOpen(Session session , @RequestParam("account")String account,@RequestParam("channel")String channel,@RequestParam("ticket")String ticket) throws Exception {
        String s = MiscUtil.verifyToken(ticket);
        if (s != null && s.equals(channel)) {
            if (CHATMAP.get(channel) == null || CHATMAP.get(channel).isEmpty()) {
                CHATMAP.put(channel, new ConcurrentHashMap<>());
            }
            CHATMAP.get(channel).put(account, session);
            if(rooominfoService.queryById(Integer.parseInt(channel)).getRoom_type()!=0) {
                getfirstsong(channel,session);
            }
            updateonline(channel);
        }
    }
    void getfirstsong(String channel,Session session){
        BoundListOperations boundListOperations = redisTemplate.boundListOps(channel);
        Long len=boundListOperations.size();
        if (boundListOperations.size() != 0) {
            JSONObject  song = JSON.parseObject(boundListOperations.index(0).toString());
            song.put("since", (SongTask.channelhome.get(channel)==null?System.currentTimeMillis()+100:SongTask.channelhome.get(channel)) / 1000);
            song.put("type", "playSong");
            song.put("count",len-1);
            session.sendText(song.toJSONString());
        }
    }
    void updateonline(String channel){
        JSONObject online = new JSONObject();
        online.put("type","online");
        online.put("channel",channel);
        List<Integer> list=new Vector<Integer>();
        for(String x: CHATMAP.get(channel).keySet()){
            try{
                list.add(Integer.parseInt(x));
            }catch (Exception e){
                //do nothing
            }
        }
        online.put("data",list);
        SendForALL(channel,online.toJSONString());
    }
    @OnMessage
    public void onMessage(Session session,String message,  @RequestParam("account")String account,@RequestParam("channel")String channel,@RequestParam("ticket")String ticket){
         if(message.equals("bye")){
             onClose(session,account,channel);
         }
    }
    @OnClose
    public void onClose(Session session,  @RequestParam("account")String account,@RequestParam("channel")String channel) {
        try {
            session.close();
            CHATMAP.get(channel).remove(account);
        } catch (Exception e) {
            //do nothing
        }
    }
    void SendForALL(String room_id, String message) {
        ConcurrentHashMap<String, Session> stringSessionConcurrentHashMap = core.CHATMAP.get(room_id);
        if (stringSessionConcurrentHashMap == null) {
            return;
        }
        for (Session value : stringSessionConcurrentHashMap.values()) {
            value.sendText(message);
        }
    }
}
